import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import CityList from '../views/CityList.vue'
import Movie from '../views/Movie.vue'
import ComingSoon from '../views/ComingSoon.vue'
import MyCenter from '../views/MyCenter.vue'
import Hot from '../views/Hot.vue'
import Theater from '../views/Theater.vue'
import Login from '../views/Login.vue'
import Buy from '../views/Buy.vue'
import Desktop from '../views/Desktop.vue'
var MobileDetect = require('mobile-detect')
Vue.use(VueRouter);

const routes = [

  {
    path: "/",
    name: 'home',
    redirect: '/home',
    // alias: '/root' // 起别名,迷惑用户地址

  },
  {
    path: '/city-list',
    name: 'citylist',
    component: CityList
  },
  {
    path: '/home',
    redirect: '/home/movie',
    name: 'home',
    component:Home,
    // 按需加载（懒加载）
    // component: import(/* webpackChunkName: "home" */ '../views/Home.vue'),
    children: [
      {
        path: 'movie',
        redirect: '/home/movie/hot',
        component: Movie,
        name: 'movie',
        children: [
          {
            path: 'hot',
            name: 'hot',
            component: Hot
          },
          {
            path: 'comingsoon',
            name: 'comgingsoon',
            component: ComingSoon
          },
        ]

      },
      {
        path: 'theater',
        name: 'theater',
        component: Theater
      },
      {
        path: 'mycenter',
        name: 'mycenter',
        component: MyCenter,
        // meta: {
        //   needLogin: true
        // }
      },
      {
        path: '/login',
        name: 'login',
        component: Login
      },
      {
        path: '/buy',
        name: 'buy',
        component: Buy
      },
      {
        path: '/desktop',
        name: 'desktop',
        component: Desktop
      }
    ]
  }

];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});
const md = new MobileDetect(window.navigator.userAgent);
// console.log(window.navigator.userAgent);



// 易爆错点:Maximum call stack size exceeded 调用栈太多导致内存溢出 
router.beforeEach((to, from, next) => {
  // 用户验证
  // 平台检测 (检测用户代理，判断是移动平台还是PC平台)
  // console.log(md.mobile());
  if (md.mobile()) {
    // 如果是移动端，则进入网站
    // 如果当前网站需要验证用户同时用户未登录，则跳转到登录
    if (to.meta.needLogin) {
      return next("/login")
    }
    return next();
  } else {
    // 如果是桌面端，需要跳转到/desktop,但是要避免当前的url就是desktop,
    // 否则会陷入死循环，因为每一次调用next都会导致再次进入导航守卫
    console.log(to);

    if (to.path === "/desktop") {
      // 如果当前地址，/desktop
      return next();
    }
    return next('/desktop');
  }

})

export default router;
